package cn.itcast.bos.web.action.base;

import cn.itcast.bos.domain.base.Area;
import cn.itcast.bos.service.base.AreaService;
import cn.itcast.bos.utils.PinYin4jUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.io.IOException;
import java.util.*;

/**
 * @author ChuanJing
 * @date 2017年10月7日 下午3:55:12
 *  * @version 1.0
 */
@Controller
public class AreaController {

    // 注入业务层对象
    @Autowired
    private AreaService areaService;

    // 批量区域数据导入
    @RequestMapping("area_batchImport")
    public void batchImport(MultipartFile file) throws IOException {

        List<Area> areas = new ArrayList<>();

        // 编写解析代码逻辑
        // 基于.xls 格式解析 HSSF
        // 1、 加载Excel文件对象
        HSSFWorkbook hSSFWorkbook = new HSSFWorkbook(file.getInputStream());
        // 2、 读取一个sheet
        HSSFSheet sheet = hSSFWorkbook.getSheetAt(0);

        // 3、 读取sheet中每一行；一行数据 对应 一个区域对象
        for (Row row : sheet) {
            // 第一行 跳过
            if (row.getRowNum() == 0) {
                continue;
            }

            // 跳过空行
            if (row.getCell(0) == null || StringUtils.isBlank(row.getCell(0).getStringCellValue())) {
                continue;
            }

            Area area = new Area();
            area.setId(row.getCell(0).getStringCellValue());
            area.setProvince(row.getCell(1).getStringCellValue());
            area.setCity(row.getCell(2).getStringCellValue());
            area.setDistrict(row.getCell(3).getStringCellValue());
            area.setPostcode(row.getCell(4).getStringCellValue());
            area = getCode(area);
            areas.add(area);
        }

        // 调用业务层
        areaService.saveBatch(areas);
    }

    // 分页列表查询
    @RequestMapping("area_pageQuery")
    @ResponseBody
    public Map<String, Object> pageQuery(int page, int rows, Area model) {
        // 构造分页查询对象
        Pageable pageable = new PageRequest(page - 1, rows);

        // 构造条件查询对象
        Specification<Area> specification = new Specification<Area>() {
            @Override
            public Predicate toPredicate(Root<Area> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                // 创建保存条件集合对象
                List<Predicate> list = new ArrayList<Predicate>();

                // 添加条件
                if (StringUtils.isNotBlank(model.getProvince())) {
                    // 根据省份查询  模糊
                    Predicate p1 = cb.like(root.get("province").as(String.class), "%" + model.getProvince() + "%");
                    list.add(p1);
                }

                if (StringUtils.isNotBlank(model.getCity())) {
                    // 根据城市查询  模糊
                    Predicate p2 = cb.like(root.get("city").as(String.class), "%" + model.getCity() + "%");
                    list.add(p2);
                }
                if (StringUtils.isNotBlank(model.getDistrict())) {
                    // 根据区域查询  模糊
                    Predicate p3 = cb.like(root.get("district").as(String.class), "%" + model.getDistrict() + "%");
                    list.add(p3);
                }
                return cb.and(list.toArray(new Predicate[0]));
            }
        };

        // 调用业务层完成查询
        Page<Area> pageData = areaService.findPageData(specification, pageable);

        // 返回数据
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("total", pageData.getTotalElements());
        result.put("rows", pageData.getContent());

        return result;
    }
    //获取城市简拼等信息
    @RequestMapping("area_info")
    @ResponseBody
    public Area getInfo(String areaInfo) {
        String[] areaData = areaInfo.split("/");
        Area area = new Area();
        area.setProvince(areaData[0]);
        area.setCity(areaData[1]);
        area.setDistrict(areaData[2]);
        return  getCode(area);
    }

    @RequestMapping("area_save")
    public String save(Area model,String areaInfo) {
        String id = model.getId();
        //增加需要给一个id
        if (StringUtils.isEmpty(id)) {
            model.setId(UUID.randomUUID().toString());
        }
        String[] areaData = areaInfo.split("/");
        model.setProvince(areaData[0]);
        model.setCity(areaData[1]);
        model.setDistrict(areaData[2]);
        areaService.save(model);
        return "redirect:./pages/base/area.html";
    }

    @RequestMapping("area_delete")
    public String save(String[] ids) {
        areaService.delete(ids);
        return "redirect:./pages/base/area.html";
    }

    //查询所有
    @RequestMapping("area_findAll")
    @ResponseBody
    public List<Area> findAll(){
        List<Area> list = areaService.findAll();
        return list;
    }
    //创建简拼跟城市编码
    public Area getCode(Area area) {
        // 基于pinyin4j生成城市编码和简码
        String province = area.getProvince();
        String city = area.getCity();
        String district = area.getDistrict();

        // 去掉省市区的最后一个字
        province = province.substring(0, province.length() - 1);
        city = city.substring(0, city.length() - 1);
        district = district.substring(0, district.length() - 1);

        // 简码
        String[] headArray = PinYin4jUtils.getHeadByString(province + city + district);
        StringBuffer shortcode = new StringBuffer();
        for (String headStr : headArray) {
            shortcode.append(headStr);
        }
        area.setShortcode(shortcode.toString());

        // 城市编码
        String citycode = PinYin4jUtils.hanziToPinyin(city, "");
        area.setCitycode(citycode);
        return area;
    }
}